<?php

/**
 * Created by phpstorem.
 * User: yangakw@qq.com
 * Sign: 猥琐发育，别浪
 * Date: 2018-06-23
 * Time: 上午 9:59
 */
class User extends CI_Model
{
    public function by_openid($openid)
    {
        $data = $this->db->where("openid",$openid)->from('user')->get()->row();
        if(empty($data)){
            $this->load->library('WxPayPubHelper/SDKRuntimeException.php');
            $this->load->library('WxPayPubHelper/WxPaypubconfig.php');
            $this->load->library('WxPayPubHelper/WxPayPubHelper.php');
            $jsApi = new \JsApi_pub();
            $user_info = $jsApi->user_info($openid);
            if( isset($user_info['errcode']) ){
                var_dump($user_info);die;
            }
            $open_id = $user_info["openid"];;
            $nickname = isset($user_info["nickname"])?$user_info["nickname"]:$open_id;
            $headimgurl = isset($user_info["headimgurl"])?$user_info["headimgurl"]:'https://www.baidu.com/img/bd_logo1.png';
            $data = [
                "openid"=>$open_id,
                "nickname"=>$nickname,
                "headimg"=>$headimgurl,
                "weixin"=>json_encode($user_info),
            ];
            $this->db->insert("user",$data);
            $data = $this->db->where("openid",$openid)->from('user')->get()->row();
        }
        return $data;
    }
    public function save($data){
        $openid = isset($data["openid"])?$data["openid"]:'';
        if(empty($openid)){
            return false;
        }
        $data = $this->db->where("openid",$openid)->from('user')->get()->row();
        if(empty($user)){
            $this->db->insert("user",$data);
        }else{
            $this->db->where('id', $user->id);
            $this->db->update('user', $data);
        }
        return true;
    }
}